package com.qilu.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/**
 * JWT的工具类
 *
 * @author hsx
 */
@Data
@Slf4j
public class JwtUtils {

    private static final String SECRET = "asdaasdasdas";
    private static final String HEADER = "Authorization";
    private static final String TOKEN_PREFIX = "Bearer ";

    /**
     * 通过id生成token
     *
     * @param id
     * @return
     */
    public static String createToken(Integer id,Integer role) {
        String token = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject(id.toString())
                .claim("id", id.toString())
                .claim("role", role.toString())
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        return TOKEN_PREFIX + token;
    }

    /**
     * 解析出token中的负载
     *
     * @param token
     * @return
     */
    public static Claims getClaimByToken(String token) {
        token =  token.split(" ")[1];
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (RuntimeException e) {
            log.error("JWT格式异常：{},异常类型：{},全部信息：{}",e.getMessage(),e.getClass(),e);
            return null;
        }
        return claims;
    }

//
//    /**
//     * 通过token获取用户id
//     *
//     * @param request
//     * @return
//     */
//    public static Integer getUserIdByToken(ServerHttpRequest request) {
//        String token = request.getHeaders().getFirst(HEADER);
//        if(StringUtils.isBlank(token)){
//            return null;
//        }
//        Claims claims = getClaimByToken(token);
//        if(claims == null){
//            return null;
//        }
//        return Integer.valueOf(claims.getSubject());
//
//    }

    public static String getTokenByRequest(HttpServletRequest request) {
        return request.getHeader(HEADER);
    }
}